﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using TXLooker.Common.Core;
using TXLooker.Common.Debuging;
using TXLooker.Common.EventHandling;

namespace TXLooker.Common.Extentions
{
    public class ExtensionStarter: BackgroundWorker
    {
        private IList<IExtentionEntryPoint> extensionsToInitialize;
        private IExtentionDataProvider extensionDataProvider;
        private EventSink eventSink;

        public ExtensionStarter(IList<IExtentionEntryPoint> extensions, IExtentionDataProvider dataProvider, EventSink sink)
        {
            extensionsToInitialize = extensions;
            extensionDataProvider = dataProvider;
            eventSink = sink;

            WorkerReportsProgress = true;
            WorkerSupportsCancellation = true;
        }

        const int percentMin = 0;
        const int percentMax = 100;

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            ReportProgress(percentMin, "TX Looker Extensions: Initializing...");

            int percents = percentMin;
            int percentAdd = percentMax/extensionsToInitialize.Count;

            IList<IExtentionEntryPoint> initializedExtensions = new List<IExtentionEntryPoint>();

            foreach(IExtentionEntryPoint entryPoint in extensionsToInitialize)
            {
                ReportProgress(percents, String.Format("TX Looker Extensions: Initializing ({0})...", entryPoint.Name));

                if(CancellationPending)
                {
                    e.Cancel = true;
                    e.Result = initializedExtensions;
                    return;
                }

                try
                {
                    entryPoint.EventSink = eventSink;
                    entryPoint.StartUp(extensionDataProvider);

                    initializedExtensions.Add(entryPoint);
                }
                catch (Exception ex)
                {
                    string ErrorStr = string.Format("Extention '{0}' Error {1}", entryPoint.GetType(), ex);
                    LogManager.WriteMessageToCustomLog(ErrorStr);
                    DebugManager.ShowErrorDescription(ErrorStr);
                }

                percents += percentAdd;
            }

            e.Result = initializedExtensions;

            ReportProgress(percentMax, "TX Looker Extensions: Initialized.");
        }
    }
}
